﻿using LogService;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace ConfigService
{
    public class IniFileConfigService : IConfigService
    {
        public string FileName { get; set; }

        private Dictionary<string, string> readAllFileValue = new Dictionary<string, string>();

        private readonly ILogService _log;

        public IniFileConfigService(ILogService log) 
        {
            this._log = log;
        }

        public IniFileConfigService(string fileName)
        {
            this.FileName = fileName;
            InitAllDic();
        }

        public IniFileConfigService()
        {
           
        }

        public string GetValue(string name)
        {
            string val = string.Empty;
            if (readAllFileValue.ContainsKey(name))
            {
                val = readAllFileValue[name];
            }
            return val;
        }

        private void InitAllDic()
        {
            if (File.Exists(FileName))
            {
                string[] readArr = File.ReadAllLines(FileName);
                foreach (string itemStr in readArr)
                {
                    string[] itemArr = itemStr.Trim().Split('=');
                    if (itemArr.Length == 2)
                    {
                        this.readAllFileValue[itemArr[0]] = itemArr[1];
                    }
                }
            }
        }

        public bool AddOREditKeyValue(string key, string val)
        {
            this.readAllFileValue[key] = val;
            return true;
        }

        public bool SaveAll()
        {
            List<string> ls = new List<string>();
            foreach (var kvp in this.readAllFileValue)
            {
                ls.Add($"{kvp.Key}={kvp.Value}");
            }
            try
            {
                File.WriteAllLines(FileName, ls);
            }
            catch (Exception ex)
            {
                _log.Log(LogLeve.Error, string.Format($"save configInfo error. type{ex.GetType()} ex:{ex.Message}"));
                return false;
            }
            return true;
        }

        public bool ExistFileName()
        {
            return File.Exists(FileName);
        }
    }
}
